package com.fucius.study.leetcode;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

public class FooBar {
    private int n;
    Semaphore semaphore = new Semaphore(10);
    CountDownLatch cda = new CountDownLatch(1);
    CountDownLatch cdb = new CountDownLatch(0);

    public FooBar(int n) {
        this.n = n;
    }

    public void foo() throws InterruptedException {

        for (int i = 0; i < n; i++) {
//            CountDownLatch cd = cdb;
            cdb.await();
            System.out.print("foo");
            cdb = new CountDownLatch(1);
            cda.countDown();
        }
    }

    public void bar() throws InterruptedException {

        for (int i = 0; i < n; i++) {
            cda.await();
            System.out.print("bar");
            cda = new CountDownLatch(1);
            cdb.countDown();
            // printBar.run() outputs "bar". Do not change or remove this line.

        }
    }

    public static void main(String[] args) {
        final FooBar fooBar = new FooBar(10);
        new Thread(){
            @Override
            public void run(){
                try {
                    fooBar.foo();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        new Thread(){
            @Override
            public void run(){
                try {
                    fooBar.bar();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

        List<Integer> list1 = new ArrayList<>();
        list1.add(1);

        List<Integer> list2 = new ArrayList<>(list1);
        list2.add(2);
    }
}
